package com.horay.springclouddemo.config.server.nacos.controller;

import com.alibaba.nacos.api.annotation.NacosInjected;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import static com.alibaba.nacos.api.common.Constants.DEFAULT_GROUP;

/**
 * Class description
 *
 * @author heyingcheng
 * @date 2019/11/3 18:11
 */
@RefreshScope
@RestController
public class ConfigController {

    private static final String DATA_ID = "nacos-config-server-default.yml";

    @Value("${spring.cloud.zookeeper.connect-string:unknown}")
    private String connectString;
    @Value("${redis.port:unknown}")
    private String redisPort;
    @Value("${config.dev:unknown}")
    private String configDev;
    @Value("${shared.dev:unknown}")
    private String sharedDev;

    @GetMapping("connectString")
    public String connectString(){
        return connectString.concat("<>").concat(redisPort).concat("<>").concat(configDev).concat("<>").concat(sharedDev);
    }

    @NacosInjected
    private ConfigService configService;

    @GetMapping(value = "register")
    public boolean register() {
        try {
            configService.publishConfig(DATA_ID, DEFAULT_GROUP, "spring.application.name=hello");
            return true;
        } catch (NacosException e) {
            e.printStackTrace();
            return false;
        }
    }

    @GetMapping(value = "remove")
    public boolean remove() {
        try {
            configService.removeConfig(DATA_ID, DEFAULT_GROUP);
            return true;
        } catch (NacosException e) {
            e.printStackTrace();
            return false;
        }
    }

}
